<template>
  <view class="page">
    <view class="table-nav">{{ type === '0' ? '密码登录' : '注册账号' }}
    </view>
    <view class="con">
      <block v-if="type === '0'">
        <view class="con-1">
          <u-input placeholder="请输入账号/手机号" border="bottom" clearable maxlength="11" v-model="form.phone" fontSize="14px" color="#333333"></u-input>
        </view>
        <view class="con-1">
          <u-input placeholder="请输入密码" border="bottom" clearable maxlength="12" v-model="form.password" fontSize="14px" color="#333333" password></u-input>
        </view>
        <view class="flex">
          <view class="flex-1" @click="type = '1'">注册账号</view>
          <view class="forget" @click="handleForget">忘记密码</view>
        </view>
      </block>
      <block v-else>
        <view class="con-1">
          <u-input placeholder="请输入手机号" border="bottom" clearable maxlength="11" v-model="form.phone" fontSize="14px" color="#333333"></u-input>
        </view>
        <view class="con-1">
          <u-input placeholder="请输入验证码" placeholderClass='u-input-place' v-model="form.code" border="bottom">
            <template slot="suffix">
              <u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
              <u-button @tap="getCode" :text="tips" type="success" size="mini"></u-button>
            </template>
          </u-input>
        </view>
        <view class="con-1">
          <u-input placeholder="请输入6-12位密码" border="bottom" clearable maxlength="12" v-model="form.password" fontSize="14px" color="#333333" password></u-input>
          <u-input placeholder="请确认密码" border="bottom" clearable maxlength="12" v-model="form.passwordAgain" fontSize="14px" color="#333333" password></u-input>
        </view>
        <view class="forget" @click="type = '0'">已有账号？立即登录</view>
      </block>
      <view class="tip" @click="handleChecked">
        <image src="https://www.atuanjian.com/appletStatic/static/images/u-18.png" mode="" v-if='!checked' />
        <image src="https://www.atuanjian.com/appletStatic/static/images/u-19.png" mode="" v-else />
        我已阅读并同意<span style="color: #000000;" @click.stop="handleNav('/pagesB/rich-text/index?type=' + '用户协议')">《用户协议》
        </span><span style="color: #000000;" @click.stop="handleNav('/pagesB/rich-text/index?type=' + '隐私政策')">《隐私政策》</span>
      </view>
      <view class="btn-login" @click="handleType">{{ type === '0' ? '登录' : '下一步' }}</view>
      <!-- #ifdef MP-WEIXIN -->
      <button class="btn-login" style="margin-top: 12rpx;background-color: #F2F2F2;color: #000000;" @getphonenumber="handleGetPhoneNumber" open-type="getPhoneNumber">手机号一键登录</button>
      <!-- #endif -->
      <view class="index" @click="handleNav('/pages/home/home')">前往首页</view>
    </view>
  </view>
</template>

<script>
import {
  register,
  sendCodes,
  h5Login,
  wxLogin,
  getPhoneNumber,
} from "@/utils/request.js";
import helper from "@/utils/helper.js";
export default {
  data() {
    return {
      type: "0",
      checked: false,
      form: { phone: "", password: "", code: "" },
      tips: "",
      value: "",
      phoneNumber: "",
      code: "",
    };
  },
  methods: {
    handleNav(url) {
      uni.navigateTo({
        url: url,
      });
    },
    codeChange(text) {
      this.tips = text;
    },
    async register(data) {
      return await register(data);
    },
    async h5Login(data) {
      return await h5Login(data);
    },
    async sendCodes(data) {
      return await sendCodes(data);
    },
    async wxLogin(data) {
      return await wxLogin(data);
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        if (!helper.validateInternationalPhoneNumber(this.form.phone)) {
          uni.showToast({
            title: "手机号格式不正确！",
            icon: "none",
          });
          return;
        }
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          this.sendCodes(this.form).then((res) => {
            console.log(res);
          });
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    handleChecked() {
      this.checked = !this.checked;
    },
    handleForget() {
      uni.navigateTo({
        url: "/pagesB/login/forget",
      });
    },
    async getPhoneNumber(data) {
      return await getPhoneNumber(data);
    },
    Loading(data) {
      uni.showLoading({ title: "登陆中...", mask: true });
      this.wxLogin(data)
        .then((result) => {
          console.log("result", result);
          this.userInfo = result.userInfo;
          uni.setStorageSync("userInfo", JSON.stringify(result.userInfo));
          uni.hideLoading();
          uni.redirectTo({
            url: "/pages/mine/mine",
          });
        })
        .catch((err) => {
          this.isLog = false;
        });
    },
    handleType() {
      if (this.type === "0") {
        this.handleLogo();
      } else {
        //注册后下一步
        if (!this.form.phone || !this.form.password || !this.form.code) {
          uni.showToast({
            title: "请输入完整信息",
            icon: "none",
          });
          return;
        }
        // this.form.username = this.form.phone;
        if(!this.checked){
          uni.showToast({
            title: "请先阅读并同意《用户协议》《 隐私政策》 ",
            icon: "none",
          });
          return ;
        }
        this.register(this.form).then((res) => {
          if (res.code == 200) {
            // uni.showToast({
            //   title: "注册成功",
            //   icon: "none",
            // });
            // this.type = "0";
            uni.navigateTo({
              url: "./info",
            });
          }
        });
      }
    },
    handleGetPhoneNumber(e) {
      if (!this.checked) {
        uni.showToast({
          title: "请先阅读并同意《用户协议》《 隐私政策》 ",
          icon: "none",
        });
        return;
      }
      if (e.detail.errMsg == "getPhoneNumber:ok") {
        uni.login({
          success: (res) => {
            let data = {
              code: res.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
            };
            this.code = res.code;
            this.getPhoneNumber(data)
              .then((res1) => {
                this.phoneNumber = res1.phone;
                uni.setStorageSync("phone", res1.phone);
                uni.setStorageSync("token", res1.token);
                if (!res1.is_register) {
                  uni.navigateTo({
                    url: "./info",
                  });
                } else {
                  uni.setStorageSync("userInfo", JSON.stringify(res1.user));
                  uni.showToast({
                    title: "登陆成功",
                  });
                  setTimeout(() => {
                    // uni.redirectTo({
                    //   url: '/pages/mine/mine'
                    // })
                    uni.navigateBack({ delta: 1 });
                  }, 1500);
                }
              })
              .catch((err) => {});
          },
        });
      }
      return;
      uni.getUserProfile({
        desc: "用于登录",
        lang: "zh_CN",
        success: (res1) => {
          uni.showLoading({
            title: "登陆中...",
          });
          console.log("登录获取", res1);
          uni.login({
            success: (res2) => {
              console.log("登录获取", res2);
              let info = {
                avatarUrl: res1.userInfo.avatarUrl,
                nickName: res1.userInfo.nickName,
                gender: res1.userInfo.gender,
                province: res1.userInfo.province,
                city: res1.userInfo.city,
                country: res1.userInfo.country,
              };
              let data = {
                code: res2.code,
                ...info,
              };
              this.wxLogin(data)
                .then((result) => {
                  console.log("result", result);
                  // if (result.code == 200) {
                  this.userInfo = result.userInfo;
                  uni.setStorageSync(
                    "userInfo",
                    JSON.stringify(result.userInfo)
                  ); // 用户信息
                  uni.hideLoading();
                  // // phoneBinding
                  // uni.setStorageSync("phone", result.phoneBinding);
                  uni.redirectTo({
                    url: "/pages/mine/mine",
                  });
                })
                .catch((err) => {
                  this.isLog = false;
                });
            },
            fail: (err) => {
              this.isLog = false;
            },
          });
        },
        fail: (err) => {
          uni.showToast({
            title: "拒绝访问个人信息可能会导致部分功能无法正常使用",
            icon: "none",
            duration: 3000,
          });
          this.isLog = true;
        },
      });
    },
    handleLogo() {
      if (!this.checked) {
        uni.showToast({
          title: "请先阅读并同意《用户协议》《 隐私政策》",
          icon: "none",
        });
        return;
      }
      if (this.type === "0") {
        //登陆
        if (!this.form.phone || !this.form.password) {
          uni.showToast({
            title: "请输入完整信息",
            icon: "none",
          });
          return;
        }
        this.h5Login(this.form).then((res) => {
          console.log("res", res);
          if (res) {
            // uni.setStorageSync("phone", result.phone);
            // let userInfo = result.wx_user;
            // if (!userInfo) {
            //   userInfo = {
            //     nickName: result.username,
            //     phone: result.phone,
            //   };
            // }
            // userInfo.token = result.token;
            // this.userInfo = userInfo;
            uni.setStorageSync("userInfo", JSON.stringify(res.user));
            uni.setStorageSync("phone", res.phone);
            uni.setStorageSync("token", res.token);
            uni.showToast({
              title: "登陆成功",
            });
            setTimeout(() => {
              // uni.redirectTo({
              //   url: '/pages/mine/mine'
              // })
              uni.navigateBack({ delta: 1 });
            }, 1500);
            // uni.redirectTo({
            //   url: "/pages/mine/mine",
            // });
          }
        });
      } else {
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background-image: linear-gradient(to bottom, #ffb850, #f2f2f2, #ffffff);

  ::v-deep .u-border-bottom {
    border-color: #7f7f7f !important;
  }

  .index {
    font-size: 30rpx;
    text-align: center;
    margin: 62rpx auto 0;
    color: #000000;
  }

  .flex {
    justify-content: space-between;
    font-size: 26rpx;
    width: 100%;
    margin: 24rpx auto 0;

    .flex-1 {
      color: #ffbb50;
    }
  }

  .forget {
    font-size: 26rpx;
    text-align: right;
    color: #555555;
  }

  .table-nav {
    margin-left: 43rpx;
    font-size: 44rpx;
    font-weight: bold;
    padding-top: 135rpx;
  }

  .con {
    width: 665rpx;
    margin: 80rpx auto 0;

    .con-1 {
      font-size: 30rpx;
      margin-bottom: 16rpx;
    }

    .con-input {
      width: 625rpx;
      padding: 24rpx 20rpx;
      margin-top: 16rpx;
      border-bottom: 1rpx solid #7f7f7f;
      font-size: 28rpx;
    }

    .tip {
      display: flex;
      align-items: center;
      font-size: 27rpx;
      color: #7f7f7f;
      margin: 20rpx auto 0;

      image {
        width: 30rpx;
        height: 30rpx;
        margin-right: 8rpx;
      }
    }

    .btn-login {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #ffb850;
      border-radius: 16rpx;
      text-align: center;
      border: 1rpx solid #ffb850;
      margin-top: 20rpx;
      font-size: 30rpx !important;
      color: #ffffff;
    }
  }
}

::v-deep .u-border {
  border: 1rpx solid #797979 !important;
}

::v-deep .u-input {
  padding: 24rpx 20rpx !important;
  margin-top: 16rpx !important;
  font-size: 28rpx !important;
}

::v-deep.input-placeholder {
  color: #7f7f7f !important;
}

::v-deep.u-input-place {
  color: #7f7f7f !important;
  font-weight: 400;
  font-size: 28rpx !important;
}

/deep/.u-button {
  background-color: #ffb850 !important;
  border: 1rpx solid #ffb850 !important;
}

::v-deep.u-button--success {
  background-color: #ffb850 !important;
  border: 1rpx solid #ffb850 !important;
}
</style>